package com.qfmy.service.impl.novel;


import com.qfmy.mapper.novel.NovelMapper;
import com.qfmy.mapper.novel.RatingMapper;
import com.qfmy.service.novel.RatingService;
import common.exception.BaseException;
import common.login.LoginUser;
import common.login.LoginUserHolder;
import common.result.ResultCodeEnum;

import lombok.extern.slf4j.Slf4j;
import model.entity.novel.Rating;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author 清风明月
 * @Package com.qfmy.service.impl.novel
 * @date 2025/6/7
 * @description 评分
 */
@Slf4j
@Service
@SuppressWarnings("all")
public  class RatingServiceImpl implements RatingService {

    /**
     * 注入mapper
     */
    @Autowired
    private RatingMapper ratingMapper;

    /**
     * 注入小说mapping
     */
    @Autowired
    private NovelMapper novelMapper;
    /**
     * 注入mq模板
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 获取评分
     * @param novelId
     * @return
     */
    @Override
    public Double getRating(@NotNull Long novelId) {
        //获取用户id
        Long userId = getUserId();
        //根据小说id和用户id获取评分
        Double score = ratingMapper.getRating(novelId, userId);
        return score;
    }

    /**
     * 对小说进行评分
     * @param novelId
     * @param score
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setRating(Long novelId, Double score) {
        Long userId = getUserId();
        //创建一个评分对象
        Rating rating = new Rating();
        rating.setNovelId(novelId);
        rating.setUserId(userId);
        rating.setRating(score);
        ratingMapper.setRating(rating);
        //发送mq消息
        rabbitTemplate.convertAndSend("rating.exchange","rating.key",rating);
    }

    /**
     * 获取用户id
     * @return
     */
    public Long getUserId() {
        //判断是否存在
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        if(loginUser == null)
        {
            throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return loginUser.getUserId();
    }
}
